import React, { Component } from 'react';
import IceContainer from '@icedesign/container';
import PropTypes from 'prop-types';
import { Input, Grid, Button, Switch, Select, Feedback, Upload } from '@icedesign/base';
import {
  FormBinderWrapper as IceFormBinderWrapper,
  FormBinder as IceFormBinder,
  FormError as IceFormError,
} from '@icedesign/form-binder';
const { ImageUpload } = Upload
const { Row, Col } = Grid;
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/index.css';
import { UploadService, AmberService } from '../../services'
import { hashHistory } from 'react-router';

export default class Add extends Component {
  static displayName = 'Add';

  static propTypes = {
  };

  static defaultProps = {};

  constructor(props) {
    super(props);
    this.state = {
      value: {
        title: '',
        image : '',
        location : '1',
        content : BraftEditor.createEditorState(''),
        status : 0,
        enable: false,
      },
    };
  }

  formChange = (value) => {
    this.setState({ value });
  };

  handleChange = (content) =>{
    let value = this.state.value
    value.content = content
    this.setState({value})
  }

  validateAllFormField = () => {
    this.setState({loading : true})
    this.refs.form.validateAll(async(errors, values) => {
      if (errors) { this.setState({loading : false}); return; }
      let image = values.image.fileList ? values.image.fileList[0] : values.image[0]
      values.image = image.imgURL
      values.status = values.enable ? 1 : 0
      values.content = this.state.value.content.toHTML()
      await AmberService.save(values)
      Feedback.toast.success('提交成功');
      hashHistory.push({ pathname:`/index` })
      this.setState({loading : false})
    });
  };

  uploadFormat = (res) =>{
    return { 
      code: res.success ? '0' : '1', 
      imgURL: res.data.filename
    };
  }

  handleUpload = async(param) =>{
    let response = await UploadService.upload(param.file)
    param.success({
      url: response.filename
    })
  }

  render() {
    return (
      <div className="user-form">
        <IceContainer>
          <IceFormBinderWrapper value={this.state.value} onChange={this.formChange} ref="form">
            <div style={styles.formContent}>
              <h2 style={styles.formTitle}>添加广告</h2>

              <Row style={styles.formItem}>
                <Col xxs="6" s="3" l="3" style={styles.formLabel}>标题:</Col>
                <Col s="12" l="10">
                  <IceFormBinder name="title" required max={50} message="标题必填">
                    <Input size="large" placeholder="请输入标题" style={{ width: '100%' }} />
                  </IceFormBinder>
                  <IceFormError name="title" />
                </Col>
              </Row>

              <Row wrap style={styles.formItem}>
                <Col xxs="7" s="4" l="3" style={styles.formLabel}>图片：</Col>
                <Col xxs="16" s="10" l="7">
                  <IceFormBinder name="image" required message="必填">
                      <ImageUpload action="/api/upload/file" listType="picture-card" limit={1}
                          locale={{ image: { cancel: '取消上传', addPhoto: '上传图片', } }}
                          accept="image/png, image/jpg" formatter={this.uploadFormat}/> 
                  </IceFormBinder>
                  <IceFormError name="image" />
                </Col>
              </Row>

              <Row style={styles.formItem}>
                <Col xxs="6" s="3" l="3" style={styles.formLabel}>内容:</Col>
                <Col s="12" l="21">
                  <BraftEditor value={this.state.value.content} height={500} contentFormat={'html'}
                    onChange={this.handleChange} media={{image : true,video : false,audio : false,uploadFn : this.handleUpload}}/>
                </Col>
              </Row>

              <Row style={styles.formItem}>
                <Col xxs="6" s="3" l="3" style={styles.formLabel}>广告栏位:</Col>
                <Col s="12" l="10">
                  <IceFormBinder name="location" required message="广告栏位必填">
                    <Select>
                      <Select.Option value="1">头部</Select.Option>
                      <Select.Option value="2">尾部</Select.Option>
                    </Select>
                  </IceFormBinder>
                  <IceFormError name="location" />
                </Col>
              </Row>

              <Row style={styles.formItem}>
                <Col xxs="6" s="3" l="3" style={styles.formLabel}>是否发布:</Col>
                <Col s="12" l="10">
                  <IceFormBinder name="enable">
                    <Switch defaultChecked={this.state.value.enable}/>
                  </IceFormBinder>
                  <IceFormError name="enable" />
                </Col>
              </Row>

            </div>
          </IceFormBinderWrapper>

          <Row style={{ marginTop: 20 }}>
            <Col offset="3">
              <Button type="primary" loading={this.state.loading} disabled={this.state.loading} onClick={this.validateAllFormField}> 提 交 </Button>
            </Col>
          </Row>
        </IceContainer>
      </div>
    );
  }
}

const styles = {
  formContent: {
    width: '100%',
    position: 'relative',
  },
  formItem: {
    marginBottom: 25,
  },
  formLabel: {
    height: '32px',
    lineHeight: '32px',
    textAlign: 'right',
    paddingRight : '5px',
  },
  formTitle: {
    margin: '0 0 20px',
    paddingBottom: '10px',
    borderBottom: '1px solid #eee',
  },
};
